// 全局状态管理模型
import { useState, useCallback } from 'react';
import type { UserProfile } from '@/services/generated/src/index';
import { apiClients, tokenManager } from '@/services/apiClient';

// 全局状态接口
export interface GlobalState {
  currentUser?: UserProfile;
  isLoggedIn: boolean;
  loading: boolean;
}

const useGlobal = () => {
  const [globalState, setGlobalState] = useState<GlobalState>({
    currentUser: undefined,
    isLoggedIn: !!tokenManager.getToken(),
    loading: false,
  });

  // 获取当前用户信息
  const fetchCurrentUser = useCallback(async () => {
    try {
      setGlobalState(prev => ({ ...prev, loading: true }));
      const response = await apiClients.auth.authMeRetrieve();
      const userData = (response as any).data || response;

      setGlobalState(prev => ({
        ...prev,
        currentUser: userData,
        isLoggedIn: true,
        loading: false,
      }));

      return userData;
    } catch (error) {
      setGlobalState(prev => ({
        ...prev,
        currentUser: undefined,
        isLoggedIn: false,
        loading: false,
      }));
      throw error;
    }
  }, []);

  // 登录
  const login = useCallback((user: UserProfile) => {
    setGlobalState(prev => ({
      ...prev,
      currentUser: user,
      isLoggedIn: true,
    }));
  }, []);

  // 登出
  const logout = useCallback(() => {
    tokenManager.removeToken();
    setGlobalState({
      currentUser: undefined,
      isLoggedIn: false,
      loading: false,
    });
  }, []);

  // 更新用户信息
  const updateUser = useCallback((user: Partial<UserProfile>) => {
    setGlobalState(prev => ({
      ...prev,
      currentUser: prev.currentUser ? { ...prev.currentUser, ...user } : undefined,
    }));
  }, []);

  return {
    ...globalState,
    fetchCurrentUser,
    login,
    logout,
    updateUser,
  };
};

export default useGlobal;
